package com.example.booksearch;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/OldBookSearchServlet")
public class OldBookSearchServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // 获取前端表单提交的图书关键词
        String keyword = request.getParameter("searchInput");

        // 简单模拟根据关键词查找图书，创建一个包含书籍信息的列表（实际中会从数据库查询获取）
        List<Book> books = new ArrayList<>();
        if ("java".equals(keyword)) { // 这里简单以关键词"java"为例模拟返回结果
            books.add(new Book("Effective Java", "Joshua Bloch"));
            books.add(new Book("Core Java", "Cay Horstmann"));
        }

        // 输出HTML内容到前端页面，先输出一个标题
        out.println("<h2>Search Results:</h2>");
        if (books.size() > 0) {
            // 遍历书籍列表，输出每本图书的信息
            for (Book book : books) {
                out.println("<div><h3>" + book.getTitle() + "</h3><p>Author: " + book.getAuthor() + "</p></div>");
            }
        } else {
            out.println("<p>No books found for the given keyword.</p>");
        }
    }

    // 简单的书籍内部类，用于封装书籍信息（实际可单独创建实体类文件）
    private class Book {
        private String title;
        private String author;

        public Book(String title, String author) {
            this.title = title;
            this.author = author;
        }

        public String getTitle() {
            return title;
        }

        public String getAuthor() {
            return author;
        }
    }
}
